//
//  NFSWeChatHelper.h
//  NetEaseFinancial
//
//  Created by 吴玉峰 on 8/30/15.
//  Copyright (c) 2015 吴玉峰. All rights reserved.
//

#import "WYFSinaWeiboHelper.h"

#import "WYFShareHolder.h"

static const CGFloat SHARE_IMG_COMPRESSION_QUALITY = 0.5;
static NSString *const kWeiboRedirectUrl = @"http://www.sina.com";

@interface WYFSinaWeiboHelper ()

@end

@implementation WYFSinaWeiboHelper

- (void)shareOnSinaWeibo:(WYFShareHolder *)holder {
    [self p_shareOnSinaWeiboBase:holder];
}

- (void)p_shareOnSinaWeiboBase:(WYFShareHolder *)holder {
    __weak __typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *imgUrl = [NSURL URLWithString:holder.imgUrl];
        __block UIImage *thumbImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:imgUrl]];
        dispatch_sync(dispatch_get_main_queue(), ^{
            __strong __typeof(weakSelf) strongSelf = weakSelf;
            [strongSelf p_shareWithThumbImage:holder thumbImage:thumbImage];
        });
    });
}

- (void)p_shareWithThumbImage:(WYFShareHolder *)holder thumbImage:(UIImage *)thumbImage {
    WBAuthorizeRequest *authRequest = [WBAuthorizeRequest request];
    if (self.redirectUrl != nil) {
        authRequest.redirectURI = self.redirectUrl;
    } else {
        authRequest.redirectURI = kWeiboRedirectUrl;
    }

    authRequest.scope = @"all";

    WBMessageObject *messageToShare = [self messageToShareWithThumbImage:holder thumbImage:thumbImage];
    WBSendMessageToWeiboRequest *request =
        [WBSendMessageToWeiboRequest requestWithMessage:messageToShare authInfo:authRequest access_token:nil];

    request.userInfo = @{
        @"ShareMessageFrom" : @"SendMessageToWeiboViewController",
        @"Other_Info_1" : [NSNumber numberWithInt:123],
        @"Other_Info_2" : @[ @"obj1", @"obj2" ],
        @"Other_Info_3" : @{@"key1" : @"obj1", @"key2" : @"obj2"}
    };

    [WeiboSDK sendRequest:request];
}

- (WBMessageObject *)messageToShareWithThumbImage:(WYFShareHolder *)holder thumbImage:(UIImage *)thumbImage {

    WBMessageObject *message = [WBMessageObject message];

    WBWebpageObject *webpage = [WBWebpageObject object];
    webpage.objectID = @"identifier1";
    webpage.title = holder.title;
    webpage.description = holder.desc;
    webpage.thumbnailData = UIImageJPEGRepresentation(thumbImage, SHARE_IMG_COMPRESSION_QUALITY);
    webpage.webpageUrl = holder.webUrl;

    message.mediaObject = webpage;
    return message;
}

+ (instancetype)sharedInstance {

    static WYFSinaWeiboHelper *util;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        util = [[WYFSinaWeiboHelper alloc] init];

    });
    return util;
}

- (instancetype)init {

    static id obj = nil;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        obj = [super init];
        if (obj) {
        }

    });
    self = obj;
    return self;
}

@end
